package top.codingfly.controller.aspect;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.NoHandlerFoundException;
import top.codingfly.model.resp.common.Response;

import javax.servlet.http.HttpServletRequest;
import java.net.SocketTimeoutException;

@Slf4j
@RestControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public Response handleIllegalArgumentException(IllegalArgumentException e) {
        log.error(e.getMessage(), e);
        return convertErrorMessage(500, e.getMessage());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Response handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error(e.getMessage(), e);
        return convertErrorMessage(500, e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public Response handleException(BindException e) {
        log.error(e.getMessage(), e);
        Response response = e.getBindingResult().getFieldErrors().stream()
                .filter(item -> StringUtils.isNotBlank(item.getDefaultMessage()))
                .map(item -> convertErrorMessage(500, item.getField() + ": " + item.getDefaultMessage()))
                .findFirst()
                .orElse(null);
        return response;
    }

    @ExceptionHandler(SocketTimeoutException.class)
    public Response handleSocketTimeoutException(SocketTimeoutException e) {
        log.error(e.getMessage(), e);
        return convertErrorMessage(500, "socket timeout");
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Response handleException(HttpMessageNotReadableException e) {
        log.error(e.getMessage(), e);
        return convertErrorMessage(500, "系统内部错误");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response handleException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        Response response = e.getBindingResult().getFieldErrors().stream()
                .filter(item -> StringUtils.isNotBlank(item.getDefaultMessage()))
                .map(item -> convertErrorMessage(500, item.getField() + ": " + item.getDefaultMessage()))
                .findFirst()
                .orElse(null);
        return response;
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Response handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        log.info(request.getRequestURI()+" not support "+request.getMethod()+" http method");
        return convertErrorMessage(500, "the api not support "+request.getMethod()+" http method");
    }

    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e) {
        log.error(e.getMessage(), e);
        return convertErrorMessage(500, "系统内部错误");
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Response handle404Exception(NoHandlerFoundException e) {
        return convertErrorMessage(404, "not found");
    }

    public Response convertErrorMessage(Integer errCode, String errMsg) {
        Response responseDto = new Response();
        responseDto.setCode(errCode);
        responseDto.setMessage(errMsg);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return responseDto;
    }

}
